package com.demo.zyt.modules.app.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.util.FileCopyUtils;

import com.demo.zyt.common.dto.wechat.PurchaseSuccessDTO;
import com.demo.zyt.common.exception.RRException;
import com.demo.zyt.common.utils.AppResultEnum;
import com.google.gson.Gson;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class WeChatUtils {
	
	public static final String APP_ID = "wx04d4bdb6597aeca1";
	
	public static final String APP_SECRET = "b7b3853a22d4835ade691d248cca8218";
	
	public static final String MCH_ID = "1519825401";
	
	public static final String MCH_KEY = "b75a6b27258f1fa911e6809f3d9b966f";
	
	// 根据code获取openId
	public static final String CODE_TO_SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
	
	// 获取accessToken
	public static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
	
	// 生产小程序码
	public static final String CREATE_QRCODE_URL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s";
	
	// 统一下单
	public static final String UNIFIED_ORDER = "https://api.mch.weixin.qq.com/pay/unifiedorder";
	
	// 下单日期格式
	public static final String TIME_FORMAT = "yyyyMMddHHmmss";
	
	//单位是day
	public static final int TIME_EXPIRE = 2;
	
	// 支付回调地址
	public static final String PAY_URL_NOTIFY = "http://www.weixin.qq.com/wxpay/pay.php";
	
	// 微信调用成功标记
	public static final String WECHAT_SUCCESS = "SUCCESS";
	
	// 微信调用成功标记
	public static final String WECHAT_FAIL = "FAIL";
	
	// 模板消息-购买成功通知-ID
	public static final String PURCHASE_SUCCESS_TEMPLATE_ID = "LOOyq0fFhmwYoqQjQo35ELPNH2_nYGC7ATkAxs-GD54";
	
	// 发送模板消息URL
	public static final String SEND_TEMPLATE_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=%s";

	/**
	 * 根据code获取openId
	 * @param code
	 * @return
	 */
	public static String getOpenIdByCode(String code) {
		
		try {
			
			String code2sessionUrl = String.format(CODE_TO_SESSION_URL, APP_ID, APP_SECRET, code);
			
			log.info("code2sessionUrl is {}", code2sessionUrl);
			
			HttpClient httpClient = HttpClientBuilder.create().build();
			
			HttpGet httpGet = new HttpGet(code2sessionUrl);
			
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			
			String wechatResponse = httpClient.execute(httpGet, responseHandler);
			
			log.info("result is {}", wechatResponse);
			
			Gson gson = new Gson();
			
			Map<String, Object> accessTokenMap = gson.fromJson(wechatResponse, Map.class);
			
			log.info("accessTokenMap is {}", accessTokenMap);
			
			return String.valueOf(accessTokenMap.get("openid"));
				
			
		} catch (Exception e ) {
			
			log.error(e.getMessage());
			
			throw new RRException(AppResultEnum.SYSTEM_ERROR);
			
		}
	}

	/**
	 * 获取accessToken
	 * @return
	 */
	public static String getAccessToken() {
		
		String accessTokenUrl = String.format(ACCESS_TOKEN_URL, APP_ID, APP_SECRET);
		
		HttpClient httpClient = HttpClientBuilder.create().build();
		
		HttpGet httpGet = new HttpGet(accessTokenUrl);
		
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		
		String wechatResponse;
		try {
			wechatResponse = httpClient.execute(httpGet, responseHandler);
			
			log.info("result is {}", wechatResponse);
			
		} catch (Exception e) {
			log.error(e.getMessage());
			
			throw new RRException(AppResultEnum.SYSTEM_ERROR);
		}
		
		Gson gson = new Gson();
		
		Map<String, Object> accessTokenMap = gson.fromJson(wechatResponse, Map.class);
		
		log.info("accessTokenMap is {}", accessTokenMap);
		
		return String.valueOf(accessTokenMap.get("access_token"));
	}

	/**
	 * 生产小程序码
	 */
	public static String createQrCode(String accessToken, Integer userId, String path, Integer qrCodeId) {
		
		
		try {
		
			HttpClient httpClient = HttpClientBuilder.create().build();
			
			String accessTokenUrl = String.format(CREATE_QRCODE_URL, accessToken);
			
			HttpPost httpPost = new HttpPost(accessTokenUrl);
			
			httpPost.addHeader("Content-Type", "application/json");
			
			Map<String, String> jsonMap = new HashMap<>();
			
			jsonMap.put("scene", userId + "," + qrCodeId);
			
			Gson gson = new Gson();
			
			String jsonBody = gson.toJson(jsonMap);
			
			StringEntity stringEntity = new StringEntity(jsonBody);
			
			stringEntity.setContentEncoding("UTF-8");    
			
			stringEntity.setContentType("application/json");    
			
			httpPost.setEntity(stringEntity);
			
			HttpResponse response = httpClient.execute(httpPost);
			
			HttpEntity httpEntity = response.getEntity();
			
			File qrCodeFile = new File(path);
			
			File parentFile = qrCodeFile.getParentFile();
			
			if ( !parentFile.exists() ) {
				parentFile.mkdirs();
			}
			
			try (FileOutputStream fos = new FileOutputStream(qrCodeFile)) {
				
				FileCopyUtils.copy(httpEntity.getContent(), fos);
				
			}
			
			return ImageUtils.getImgStr(path);
			
		} catch( Exception e) {
			
			e.printStackTrace();
			
			log.error(e.getMessage());
			
			throw new RRException(AppResultEnum.SYSTEM_ERROR);
		}
		
	}

	/**
	 * 发送模板消息
	 */
	public static String sendTemplateMsg(PurchaseSuccessDTO purchaseSuccessDTO) {
		try {
			
			HttpClient httpClient = HttpClientBuilder.create().build();
			
			String sendTemplateMessageUrl = String.format(SEND_TEMPLATE_MESSAGE_URL, purchaseSuccessDTO.getAccess_token());
			
			HttpPost httpPost = new HttpPost(sendTemplateMessageUrl);
			
			httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
			
			httpPost.setHeader("Accept", "application/json");
			
			Gson gson = new Gson();
			
			String jsonBody = gson.toJson(purchaseSuccessDTO);
			
			log.info("jsonBody is {}", jsonBody);
			
			StringEntity stringEntity = new StringEntity(jsonBody, Charset.forName("UTF-8"));
			
			httpPost.setEntity(stringEntity);
			
			HttpResponse response = httpClient.execute(httpPost);
			
			HttpEntity httpEntity = response.getEntity();
			
			String result = EntityUtils.toString(httpEntity);
			
			log.info("result is {}", result);
			
			return result;
			
		} catch( Exception e) {
			
			log.error(e.getMessage());
			
			throw new RRException(AppResultEnum.SYSTEM_ERROR);
		}
		
	}
	
	/**
	 * 分转元
	 */
	public static String changeF2Y(int price) {
		return BigDecimal.valueOf(Long.valueOf(price)).divide(new BigDecimal(100)).toString();
	}

	
}
